<template>
  <ul class="video-list no-scrollbar" v-loading="loading">
    <template v-if="list.length">
      <li class="video-item" v-for="video in list" :key="video.id">
        <div class="video-detail" @click="goToInfo(video.id)">
          <img
            class="video-img"
            v-if="video.thumbnail"
            :src="video.thumbnail"
          />
          <div class="video-img-place" v-else>
            <img class="video-img" src="@/assets/imgs/video-bg.jpg" />
            <div class="video-place-text">
              <div class="place-title">{{ video.title }}</div>
              <!-- <div class="place-sub-title">{{ video.startTime }}</div> -->
            </div>
          </div>
          <div class="video-content">
            <div class="video-title overflow-text">{{ video.title }}</div>
            <div class="sub-title">
              <span>
                {{
                  isLive
                    ? `直播号：${video.meetingRoomNumber}`
                    : `${video.speaker ? `主讲人：${video.speaker}` : ""}`
                }}
              </span>
              <i
                v-if="isLive"
                class="sdlive icon-fuzhi icon"
                :data-clipboard-text="`${video.meetingRoomNumber}`"
                @click.stop="($event) => Copy($event, video.meetingRoomNumber)"
              ></i>
            </div>
            <div class="sub-title">
              <span
                v-if="isLive"
                :class="[
                  'state',
                  video.liveState === '0'
                    ? 'no-start'
                    : video.liveState === '3'
                    ? ''
                    : 'has-start',
                ]"
                >{{ LIVE_STATE[video.liveState] || "" }}</span
              >
              <template v-if="isShowLike">
                <i class="sdlive icon-foot icon-dianzan_kuai"></i>
                <span class="number">{{
                  video.thumbsUpNum >= 100 ? "99+" : video.thumbsUpNum
                }}</span>
                <i class="sdlive icon-foot icon-sc-active"></i>
                <span class="number">{{
                  video.collectNum >= 100 ? "99+" : video.collectNum
                }}</span>
              </template>
            </div>
          </div>
          <!--直播时长-->
          <div class="live-time" v-if="isLive">
            <div class="time">
              <div class="time-hs">{{ video.startHm }}</div>
              <div class="time-date">{{ video.startYmd }}</div>
            </div>
            <div class="time-line">
              <div class="state"></div>
              <div class="time-duration">
                <div class="duration-line"></div>
                <div class="duration">
                  {{ TIME_COLOBJ[video.durationTime] }}
                </div>
                <div class="duration-line"></div>
              </div>
            </div>
            <div class="time">
              <div class="time-hs">{{ video.endHm }}</div>
              <div class="time-date">{{ video.endYmd }}</div>
            </div>
          </div>
          <div class="live-time" v-else></div>
        </div>
        <div class="video-operate">
          <el-tooltip
            v-for="item in operateBtns[name]"
            :key="item.name"
            :content="item.title"
            effect="dark"
            placement="top"
          >
            <el-button
              circle
              :type="item.btnType || ''"
              :icon="item.icon"
              :plain="item.plain || false"
              @click="operateHandler(video, item.handler)"
            >
            </el-button>
          </el-tooltip>
        </div>
      </li>
    </template>
    <template v-if="!list.length && !loading">
      <li class="empty-data">
        <img src="@/assets/imgs/empty-data.png" />
        <div class="no-text">暂无数据</div>
      </li>
    </template>
  </ul>

  <div class="page-foot">
    <div class="page-spce"></div>
    <el-pagination
      v-model:current-page="page"
      small
      background
      layout="prev, pager, next"
      :total="total"
      @current-change="getData(false)"
    />
  </div>

  <!--密码验证-->
  <InputPwd ref="inputPwdRef" :password="currentLive.pwd" @pass="gotoDetail" />
</template>

<script setup>
import {
  computed,
  ref,
  watch,
  reactive,
  nextTick,
  onActivated,
  defineExpose,
  onMounted,
  onBeforeUnmount
} from 'vue'
import { useRouter } from 'vue-router'

import { useAuthStore } from '@/store/auth'

import {
  TIME_COLOBJ,
  LIVE_STATE,
  VIDEO_DEFAULT_BTNS_PC,
  VIDEO_SC_BTNS_PC,
  LIVE_DEFAULT_BTNS_PC,
  LIVE_MY_BTNS_PC,
  LIVE_SC_BTNS_PC
} from '@/source/index'

import InputPwd from '@/components/input-pwd.vue'

import { WEB_HREF } from '@/utils/index'
import { wxShare, wxSdLiveApp } from '@/utils/wx'
import { VantMessage } from '@/utils/vant-utils'
import { insertShareLog } from '@/api/share'

import Copy from '@/utils/clipboard'

import { useListCommon } from '@/hooks/useList'

const $router = useRouter()
const authStore = useAuthStore()

const props = defineProps({
  name: {
    type: String,
    default: 'live_my'
  },
  isLive: {
    type: Boolean,
    default: true
  },
  searchContext: {
    type: String,
    default: ''
  }
})

const operateBtns = {
  live_my: LIVE_MY_BTNS_PC,
  live_all: LIVE_DEFAULT_BTNS_PC,
  live_collect: LIVE_SC_BTNS_PC,
  video_collect: VIDEO_SC_BTNS_PC,
  video_all: VIDEO_DEFAULT_BTNS_PC
}

const inputPwdRef = ref(null)
const currentLive = reactive({
  id: '',
  pwd: ''
})

const loading = ref(true)

const isShowLike = computed(() =>
  ['live_all', 'live_collect', 'video_all', 'video_collect'].includes(
    props.name
  )
)

const { page, total, list, getListData, delListItem } = useListCommon()

const getData = async(isReset = false) => {
  loading.value = true
  try {
    // 刷新
    if (isReset) {
      list.value = []
      page.value = 1
      total.value = 1
    }
    // 如果加载完成不在加载
    const data = await getListData(
      props.isLive,
      props.name,
      props.searchContext
    )
    list.value = data
    loading.value = false
  } catch (error) {
    console.log('error', error)
    loading.value = false
  }
}

const operateHandler = (video, handler) => {
  //
  if (handler === 'startLive') {
    // 开始直播
    startLive(video)
  } else if (handler === 'editLive') {
    // 编辑直播
    editLive(video)
  } else if (handler === 'delItem') {
    // 移除删除
    delItem(video.id)
  } else if (handler === 'viewLive') {
    // 观看直播
    videwLive(video)
  } else if (handler === 'viewVideo') {
    // 观看点播
    $router.push({
      path: '/video-detail',
      query: {
        id: video.id
      }
    })
  } else {
    // 分享
    share(video)
  }
}

const videwLive = async(video) => {
  if (!inputPwdRef.value) {
    return
  }
  currentLive.id = video.id
  currentLive.pwd = video.meetingPassword
  await nextTick()
  inputPwdRef.value.toShowDialog(true)
}

// 去详情页
const goToInfo = (id) => {
  if (props.isLive) {
    $router.push({
      path: '/info',
      query: {
        id
      }
    })
  } else {
    $router.push({
      path: '/video-detail',
      query: {
        id
      }
    })
  }
}
const startLive = (video) => {
  if (video.userId !== authStore.userId) {
    VantMessage.warning('请登录直播创建者账户直播')
    return
  }
  if (video.liveState === '1') {
    VantMessage.warning('直播已开始')
    return
  }
  wxSdLiveApp(video.id)
}

const editLive = (video) => {
  if (video.userId !== authStore.userId) {
    VantMessage.warning('请登录直播创建者账户直播')
    return
  }
  $router.push({
    path: '/edit',
    query: {
      id: video.id
    }
  })
}

const gotoDetail = () => {
  if (!currentLive.id) {
    return
  }
  $router.push({
    path: '/live-detail',
    query: {
      id: currentLive.id,
      pass: '1'
    }
  })
}

const delItem = async(id) => {
  delListItem(id, props.name, () => {
    getData(true)
  })
}

// 分享
const share = (video) => {
  wxShare(
    {
      title: video.title,
      desc: video.briefIntroduction,
      link: `${WEB_HREF}/${props.isLive ? 'live-detail' : 'video-detail'}?id=${
        video.id
      }`
    },
    props.isLive,
    () => {
      if (props.isLive) {
        insertShareLog(video.id)
      }
    }
  )
}

// watch(
//   () => props.searchContext,
//   (val) => {
//     getData(true)
//   }
// )

defineExpose({
  getData
})
</script>

<style lang="less" scoped>
@import "@/styles/video-item.less";
@import "@/styles/mixins.less";

.video-list {
  overflow-x: hidden;
  overflow-y: auto;
  .empty-data {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    img {
      height: 180px;
    }
    .no-text {
      height: 40px;
      line-height: 40px;
      color: #949494;
      font-size: 16px;
    }
  }
  .video-item {
    /* prettier-ignore */
    .video-detail {
      width: calc(100% - 100px);
      height: 100%;
      display: flex;
      flex-direction: row;
      align-items: center;
      float: left;
    }
    .sub-title {
      height: 30px;

      display: flex;
      flex-direction: row;
      align-items: center;
      .state {
        font-size: 12px;
        padding: 3px;
        border-radius: 2px;
        color: #fff;
        line-height: 12px;
        transform: scale(0.83);
        &.no-start {
          background-color: #dc8e49;
        }
        &.has-start {
          background-color: var(--van-button-success-background);
        }
      }
    }

    .icon-foot,
    .number {
      margin-right: 5px;
    }
    .icon-fuzhi {
      font-size: 20px;
      margin-left: 10px;
      color: #326aeb;
      font-weight: bold;
    }
    .video-operate {
      width: 180px;
      height: 100%;
      float: left;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      &:deep(.el-button) {
        margin: 0 5px;
      }
    }
  }
}

.live-time {
  width: 350px;
  height: 70px;
  display: flex;
  flex-direction: row;
  margin-bottom: 10px;
  .time {
    width: 110px;
    height: 100%;
    > div {
      text-align: center;
    }
    .time-hs {
      height: 50px;
      font-size: 28px;
      color: #323337;
      line-height: 50px;
    }
    .time-date {
      font-size: 12px;
      color: #1d1e22;
      line-height: 20px;
    }
  }
  .time-line {
    flex: 1;
    height: 100%;
    padding: 0 5px;
    .state {
      width: 100%;
      height: 25px;
      margin-top: 5px;
    }
    .time-duration {
      width: 100%;
      height: 30px;
      display: flex;
      flex-direction: row;
      align-items: center;
      .duration-line {
        height: 1px;
        flex: 1;
        background-color: #dbdde2;
      }
      .duration {
        font-size: 14px;
        display: inline-block;
        padding: 2px 4px;
        margin: 0 5px;
        background-color: #edeef2;
        color: #606467;
        border-radius: 2px;
      }
    }
  }
}
</style>
